﻿#include "Purchase_Ticket_Process.h"
#include <qwidget.h>
#include <Constants.h>
#include <Global_Class.h>
#include <string>
#include <QDateTime>
#include <bookTicketPOJO.h>
using namespace Constants;


Purchase_Ticket_Process::Purchase_Ticket_Process(QWidget *parent)
	: QDialog(parent),
    start_station_id(0),  // 初始化起始站ID
    end_station_id(0)     // 初始化终点站ID
{
	ui.setupUi(this);
	connect(ui.BookTicketBtn, &QPushButton::clicked, this, &Purchase_Ticket_Process::showBookTicketInformation);
	connect(ui.Ticket_Table, &QTableWidget::cellClicked, this, &Purchase_Ticket_Process::getCurrentTicketInformation);
}

Purchase_Ticket_Process::~Purchase_Ticket_Process()
{

}


void Purchase_Ticket_Process::setupStationTable() {
    
    // 初始化表格
    ui.Ticket_Table->setColumnCount(STATION_TABLE_COLUMN_COUNT + 1); // 增加票价列
    ui.Ticket_Table->setRowCount(0);
    ui.Ticket_Table->setHorizontalHeaderLabels(
        QStringList() << "列车编号" << "起始站" << "终点站" << "出发时间" << "到达时间" << "花费时间" << "票价");

    // 创建快速查找映射
    QHash<int, std::string> stationNames; // stationID -> name
    for (auto& station : allData->stationsQueue) {
		std::string name = station.getName();
        stationNames[station.getStationId()] = name;
    }

    QHash<int, std::string> trainCodes; // trainID -> code
    for (auto& train : allData->trainQueue) {
        trainCodes[train.getTrainId()] = train.getTrainCode();
    }

    // 按列车ID分组时刻表
    QHash<int, QVector<train_schedule>> schedulesByTrain;
    for (auto& ts : allData->trainSchedules) {
        schedulesByTrain[ts.getTrainId()].append(ts);
    }

    // 处理每个列车的时刻表
    for (auto it = schedulesByTrain.begin(); it != schedulesByTrain.end(); ++it) {
        int trainId = it.key();
        processTrainSchedules(trainId, it.value(), stationNames, trainCodes);
    }
}

void Purchase_Ticket_Process::processTrainSchedules(
    int trainId,
    QVector<train_schedule>& schedules,
    QHash<int, std::string>& stationNames,
    QHash<int, std::string>& trainCodes)
{
    // 查找起始站和终点站(确保顺序)
    train_schedule* startSchedule = nullptr;
    train_schedule* endSchedule = nullptr;

    for (auto& ts : schedules) {
        if (ts.getStationId() == start_station_id) {
            startSchedule = &ts;
        }
        // 只在找到起始站后查找终点站
        if (startSchedule && ts.getStationId() == end_station_id) {
            endSchedule = &ts;
            break; // 找到有效组合即停止
        }
    }

    // 检查是否找到有效组合
    if (!startSchedule || !endSchedule) return;

    // 获取显示数据
    std::string trainCode = trainCodes.value(trainId, "未知列车");
    std::string startStation = stationNames.value(start_station_id, "未知车站");
    std::string endStation = stationNames.value(end_station_id, "未知车站");

    // 计算时间差 (处理跨天情况)
    QDateTime departTime = QDateTime::fromString(
        QString::fromStdString(startSchedule->getDepartTime()), "HH:mm");

    QDateTime arriveTime = QDateTime::fromString(
        QString::fromStdString(endSchedule->getArrivalTime()), "HH:mm");

    // 处理跨天到达 (到达时间 < 出发时间)
    if (arriveTime < departTime) {
        arriveTime = arriveTime.addDays(1);
    }

    qint64 seconds = departTime.secsTo(arriveTime);
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    QString duration = QString("%1小时%2分").arg(hours).arg(minutes);

    // 票价计算（显示三种座型）
    double priceBusiness = AllData::CalculateTicketPrice(start_station_id, end_station_id, "商务座", allData->stationsQueue);
    double priceFirst = AllData::CalculateTicketPrice(start_station_id, end_station_id, "一等座", allData->stationsQueue);
    double priceSecond = AllData::CalculateTicketPrice(start_station_id, end_station_id, "二等座", allData->stationsQueue);

    // 添加行到表格
    int row = ui.Ticket_Table->rowCount();
    ui.Ticket_Table->insertRow(row);

    ui.Ticket_Table->setItem(row, 0, new QTableWidgetItem(QString::fromStdString(trainCode)));
    ui.Ticket_Table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(startStation)));
    ui.Ticket_Table->setItem(row, 2, new QTableWidgetItem(QString::fromStdString(endStation)));
    ui.Ticket_Table->setItem(row, 3, new QTableWidgetItem(QString::fromStdString(startSchedule->getDepartTime())));
    ui.Ticket_Table->setItem(row, 4, new QTableWidgetItem(QString::fromStdString(endSchedule->getArrivalTime())));
    ui.Ticket_Table->setItem(row, 5, new QTableWidgetItem(duration));
    // 新增票价列
    ui.Ticket_Table->setItem(row, 6, new QTableWidgetItem(
        QString("商务座: %1元  一等座: %2元  二等座: %3元")
            .arg(priceBusiness < 0 ? "-" : QString::number(priceBusiness, 'f', 2))
            .arg(priceFirst < 0 ? "-" : QString::number(priceFirst, 'f', 2))
            .arg(priceSecond < 0 ? "-" : QString::number(priceSecond, 'f', 2))
    ));
}


void Purchase_Ticket_Process::getCurrentTicketInformation(int row, int column) {
	if (row < 0 || row >= ui.Ticket_Table->rowCount()) {
		return; // 确保行索引有效
	}
	bookTicket = new bookTicketPOJO(); // 创建新的购票POJO对象
	bookTicket->setTrainCode(ui.Ticket_Table->item(row, 0)->text().toStdString());
	bookTicket->setStartStation(ui.Ticket_Table->item(row, 1)->text().toStdString());
	bookTicket->setEndStation(ui.Ticket_Table->item(row, 2)->text().toStdString());
	bookTicket->setDepartTime(ui.Ticket_Table->item(row, 3)->text().toStdString());
	bookTicket->setArriveTime(ui.Ticket_Table->item(row, 4)->text().toStdString());
	bookTicket->setTimeCost(ui.Ticket_Table->item(row, 5)->text().toStdString());
}


void Purchase_Ticket_Process::showBookTicketInformation() {
	bookTicketShowWindow = new Book_Ticket_Show_Window();
	purchaseTicketProcessWindow->accept(); // 关闭购票流程窗口
	bookTicketShowWindow->show();
}